﻿using Shinva.LADModel.Abstractions;
using Shinva.Variables.Interface;
using Shinva.Variables.Models;
using Shinva.Variables.Type.bit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shinva.LADModel.Type.ComparatorOperations
{
    // 定义比较类型的枚举
    public enum ComparisonType
    {
        Eq,//等于
        Ne,//不等于
        Ge,//大于等于
        Le,//小于等于
        Gt,//大于
        Lt,//小于
        //InRange,//在范围内
        //outRange,//不在范围内
    }
    public class ComparatorTwo<T>:ElementNodeBase where T: PlcMemberBase
    {
        public T in1 { get; set; } 
        public T in2 { get; set; } 
        //重写一下使能输出的值
        public override PlcBool EN
        {
            get
            {
                return en;
            }
            set
            {
                en = value;
            }
        }
        public override PlcBool ENO
        {
            get
            {

                eno.Value = en.Value && Compare();
                return eno;
            }
            set
            {
                eno = value;
            }
        }
        // 比较类型
        private readonly ComparisonType _comparisonType;
        public ComparatorTwo(ComparisonType comparisonType)
        {
            Name = "ComparatorTwo";

            variableTableInterface.AddVariable("in1", StorageType.Input);
            variableTableInterface.AddVariable("in2", StorageType.Input);

            in1 = variableTableInterface.GetVariableValue<T>("in1");
            in2 = variableTableInterface.GetVariableValue<T>("in2");
            _comparisonType = comparisonType;
        }

        public override IPlcMember GetInterfaceVariableByName(string name)
        {
            if (name == "pre") return EN;
            else if (name == "out") return ENO;
            else return variableTableInterface.GetVariableValue<IPlcMember>(name);
        }
        //执行逻辑,参考一下add中的计算逻辑修改一下
        public bool Compare()
        {
            if(in1 == null||in2==null) return false;
            int comparisonResult = in1.Value.CompareTo(in2.Value);
            return _comparisonType switch
            {
                ComparisonType.Eq => comparisonResult == 0,
                ComparisonType.Ne => comparisonResult != 0,
                ComparisonType.Ge => comparisonResult >= 0,
                ComparisonType.Le => comparisonResult <= 0,
                ComparisonType.Gt => comparisonResult > 0,
                ComparisonType.Lt => comparisonResult < 0,
                _ => throw new InvalidOperationException("Unsupported comparison type."),
            };
        }
    }
}
